<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateParkDataAPIRequest;
use App\Http\Requests\API\UpdateParkDataAPIRequest;
use App\Models\ParkData;
use App\Models\ParkInfo;
use App\Models\User;
use App\Repositories\ParkDataRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;
use Illuminate\Support\Facades\Auth;
use Schema;


/**
 * Class ParkDataController
 * @package App\Http\Controllers\API
 */

class ParkDataAPIController extends AppBaseController
{
    /** @var  ParkDataRepository */
    private $parkDataRepository;

    public function __construct(ParkDataRepository $parkDataRepo)
    {
        $this->parkDataRepository = $parkDataRepo;
    }

    /**
     * Display a listing of the ParkData.
     * GET|HEAD /parkDatas
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $input = $request->all();
        $page = $request->input("page",1);
        $pages = $request->input("limit",15) ;

        $atime = isset($input['atime'])?$input['atime']:'';
        // 获取车场记录
        $p = new ParkData();


        if(isset($input['vpl_number']) && !empty($input['vpl_number'])){
            $p = $p->where("vpl_number", strtoupper($input['vpl_number']));
        }
        // 车场名称
        if(isset($input['type']) && is_numeric($input['type'])){
            $p =  $p->where("type", $input['type']);
        }
        // 补录时间
        if(isset($input['atime']) && !empty($input['atime'])) {
            $atime = $input['atime'];
            if (isset($atime[0]) && !empty($atime[0])) {
                $start_time = date("Y-m-d H:i:s",$atime[0]);
                $p = $p->where("created_at", '>=', $start_time);
            }
            if (isset($atime[1]) && !empty($atime[1])) {
                $start_time = date("Y-m-d H:i:s",$atime[1]);
                $p = $p->where("created_at", '<=', $start_time);
            }
        }
        $file_name = md5('park_data_'.json_encode($input)).".csv";
        if(isset($input['export']) && !empty($input['export'])) {
            if(file_exists(storage_path("app/public/".$file_name))){
                $res = [];
                $res['file_name'] = $file_name;
                return   $this->sendResponse($res, '查询成功');
            }
            $record = $p->get();
        } else {
            $record = $p->paginate($pages, array("*"), "page", $page);
        }
        $all_pay_type = config('pay');
        foreach ($record as &$val) {
            $park_arr = ParkInfo::where("park_code",$val->park_code)->value("parking_name");
            $val->park_name = $park_arr?$park_arr:'';
            $val->money = re2float($val->money/100);
            $val->pay_type_name = isset($all_pay_type[$val->pay_type])?$all_pay_type[$val->pay_type]:'';
            $val->username = $val->user_id?User::where("id",$val->user_id)->value('true_name'):'';
        }

        if(isset($input['export']) && !empty($input['export'])){
            $title = ['vpl_number'=>'车牌号','pay_type_name'=>'支付类型','type'=>'补录类型','vpl_owner'=>'车主姓名','park_name'=>'车场名称','in_time'=>'开始时间','out_time'=>'结束时间','out_time'=>'结束时间'];
            $type_arr = config('custom.auth_type');
            $export_data = [];
            foreach ($record as $val) {
                $tmp = [];
                $tmp['vpl_number'] = $val->vpl_number;
                $tmp['pay_type_name'] = $val->pay_type_name;
                $tmp['type'] = $val->type;
                $tmp['vpl_owner'] = $val->vpl_owner;
                $tmp['park_name'] = $val->park_name;
                $tmp['in_time'] = $val->in_time;
                $tmp['out_time'] = $val->out_time;
                $tmp['username'] = $val->username;
                $export_data[] = $tmp;
            }
            return $this->export($export_data,$title,$file_name);
        }

        return $this->sendResponse($record, '获取数据成功');
    }

    /**
     * Store a newly created ParkData in storage.
     * POST /parkDatas
     *
     * @param CreateParkDataAPIRequest $request
     *
     * @return Response
     */
    public function store(CreateParkDataAPIRequest $request)
    {
        $input = $request->all();
        $user = Auth::user()->toArray();
        $input['user_id'] = $user['id'];
        $input['true_name'] = $user['true_name'];
        if(isset($input['out_time']) && $input['in_time']) {
            $dura_time = strtotime($input['out_time']) - strtotime($input['in_time']);
            $input['park_duration'] = $dura_time>0?$dura_time:0;
        }
        $input['money'] = isset($input['money'])?$input['money']*100:0;

        $parkDatas = $this->parkDataRepository->create($input);
        return $this->sendResponse($parkDatas->toArray(), '添加成功');
    }

    /**
     * Display the specified ParkData.
     * GET|HEAD /parkDatas/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        /** @var ParkData $parkData */
        $parkData = $this->parkDataRepository->findWithoutFail($id);

        if (empty($parkData)) {
            return $this->sendError('不存此数据');
        }

        return $this->sendResponse($parkData->toArray(), '获取成功');
    }

    /**
     * Update the specified ParkData in storage.
     * PUT/PATCH /parkDatas/{id}
     *
     * @param  int $id
     * @param UpdateParkDataAPIRequest $request
     *
     * @return Response
     */
    public function update($id, UpdateParkDataAPIRequest $request)
    {
        $input = $request->all();

        /** @var ParkData $parkData */
        $parkData = $this->parkDataRepository->findWithoutFail($id);

        if (empty($parkData)) {
            return $this->sendError('不存此数据');
        }
        $input['money'] = isset($input['money'])?$input['money']*100:0;
        $parkData = $this->parkDataRepository->update($input, $id);

        return $this->sendResponse($parkData->toArray(), '更新成功');
    }

    /**
     * Remove the specified ParkData from storage.
     * DELETE /parkDatas/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        /** @var ParkData $parkData */
        $parkData = $this->parkDataRepository->findWithoutFail($id);

        if (empty($parkData)) {
            return $this->sendError('不存此数据');
        }

        $parkData->delete();

        return $this->sendResponse($id, '删除成功');
    }
}
